package com.yupi.springbootinit.manager;

import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * ClassName: RedisLimiterManager
 * Package: com.yupi.springbootinit.manager
 * Description:专门提供 RedisLimiter 限流基础服务的类
 *
 * @Author:
 * @Create: 2024/4/2 - 9:14
 * @Version: v1.0
 */
@Service
public class RedisLimiterManager {


    @Resource
    private RedissonClient redissonClient;


    /**
     * 限流操作
     * @param key 区分不同的限流器，比如不同的用户id 应该分别统计
     */
    public void doRateLimit(String key) {
        //根据用户的名称或id 创建限流器，每秒最多访问 2 次
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);
        rateLimiter.trySetRate(RateType.OVERALL, 2, 1, RateIntervalUnit.SECONDS);

        //每当有操作进来，需要先请求一个令牌
        boolean isCanOperate = rateLimiter.tryAcquire(1);
        if (!isCanOperate) {
            throw new BusinessException(ErrorCode.TOO_MANY_REQUEST);
        }


    }
}
